#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFileDialog>
#include <QDebug>
#include <QFileInfoList>
#include <QFileInfo>
#include <QPixmap>
#include <QThread>

#include "mythread.h"
#include "mylabel.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    auto * l = new MyLabel(this);
    l->resize(611, 341);
    l->move(40, 40);
    l->setFrameStyle(QLabel::Box);

    // 1. 创建子线程
    this->myThread = new MyThread;
    QThread  *qThread = new QThread(this);
    myThread->moveToThread(qThread);

    // 在打开目录按钮上注册信号和槽
    connect(ui->actionOpen, &QAction::triggered, [=](){
        // 1.打开目录选择框
        QString dirPath = QFileDialog::getExistingDirectory(this, "打开目录", "./");
//        qDebug() << dirPath;
        // 2. 获取路径下所有的 jpg 和 png 文件
        QDir dir(dirPath);
        dir.setFilter(QDir::Files);
        this->list = dir.entryInfoList({"*.jpg", "*.png", "*.gif"});

        // 3. 显示第一张图片
        l->setPixmap(QPixmap(list[this->index].absoluteFilePath()));
        l->setScaledContents(true);

        // 2. 启动子线程
        qThread->start();
        emit this->startThread();
    });

    // 下一张按钮
    connect(ui->nextBtn, &QPushButton::clicked, [=](){
        this->index++;
        if(this->index == this->list.size())
        {
            this->index = 0;
        }
        l->setPixmap(QPixmap(this->list[this->index].absoluteFilePath()));
    });

    // 上一张按钮
    connect(ui->prevBtn, &QPushButton::clicked, [=](){
        this->index = --this->index == -1 ? this->list.size() - 1 : this->index;
        l->setPixmap(QPixmap(this->list[this->index].absoluteFilePath()));
    });

    // 3. 连接 startThread 信号，槽要触发 supportThread 函数（提供定时信号功能）
    connect(this, &MainWindow::startThread, myThread, &MyThread::supprotThread);

    // 4. 连接 changePic 信号，槽函数中进行图片切换的业务处理
    connect(myThread, &MyThread::changePic, [=](){
        this->index = ++this->index == this->list.size() ? 0 : this->index;
        l->setPixmap(QPixmap(this->list[this->index].absoluteFilePath()));
    });

    connect(l, &MyLabel::mouseEntered, [=](){
            myThread->setRun(false);
            emit this->startThread();
        });

    connect(l, &MyLabel::mouseLeft, [=](){
         myThread->setRun(true);
         emit this->startThread();
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}
